#!/usr/bin/env python
# -*- coding: utf-8
# File Name: py2email.py
# Mail:
# Created Time: 2018-11-09
# Describe:

import sys, os
import smtplib
from email.parser import Parser

if len(sys.argv) > 2:
    toaddrs = sys.argv[1]
    sub = sys.argv[2]
    message = sys.argv[3]
else:
    print 'Error: need 3 parameters, but %d given' % len(sys.argv[1:])
    print 'script <toaddrs> <subject> <message>'
    sys.exit(1)

toaddrs = toaddrs.split()
if len(toaddrs) > 1:
    recs = ''
    for rec in toaddrs:
        recs += rec + ','
else:
    recs = toaddrs[0]

smtp_server = 'smtp.exmail.qq.com'
smtp_port = 25
mail_user = 'xxxxx'
mail_pass = 'xxxxx'

fromaddr = 'xxxxxx'

headers = Parser().parsestr('From: '+ str(fromaddr)  +'\n'
    'To: '+ str(recs)  +'\n'
    'Subject: ' + str(sub) + '\n'
    '\n'
    '' + str(message) + '\n')

try:
    smtpObj = smtplib.SMTP(smtp_server, smtp_port)
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(fromaddr, toaddrs, headers.as_string())
    print 'OK: mail send complete'
    smtpObj.quit()
except Exception as e:
    print str(e)
    print 'Error: mail send failed'

